<template>
  <!--
    角色 功能列表

    @author yangboot ${authorEmail}
    @date 2021-08-09 14:23:49
  -->
  <div class="app-container">

    <el-tree
      v-loading="loading"
      :data="options"
      node-key="id"
      :default-checked-keys="onCheckNodeIds"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      @check-change="handleCheckChange"
      ref="tree"
      default-expand-all
    >
      <!--知识点过长处理，鼠标悬浮文字弹框显示全部内容-->
      <span slot-scope="{ node }" class="custom-tree-node">
          <span> {{ node.label | ellipsis(60) }} </span>
      </span>
    </el-tree>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <span slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="appAuthSubmit"
        >确定</el-button
      >
    </span>
  </div>
</template>

<script>
import { getGitGroups, gitGroupsDatatables } from "@/api/Git";
import { uploadGitProject } from "./api";

export default {
  name: "ManagerRole",
  components: {},
  props: {
    choiceCallBack: {
      //定义一个外来方法
      type: Function, //参数类型：函数
      required: false, //是否必填：是
    },
    // 接收当前用户参数
    selectAccountId: String,
    // gittype
    selectGit: String,
    // gittypeid 
    gitTypeId: String , 
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 状态
      statusOptions: [],
      // 应用选择
      applicationOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      ManagerRoleList: [],
      // 仓库列表
      gitGroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        roleStatus: null,
        roleTitle: null,
        gitLabel: null,
        roleDesc: null,
      },
      // 搜索参数
      searchParams: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gitLabel: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
      //  菜单数据
      menusDataList: [],
      //  树形控件设置
      menusTreeProps: {
        children: "children",
        label: "resourceName",
      },
      //选中的menus内容
      functionIds: null,
      //成员管理列表查询参数
      roleMemberQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      //选中用户的id
      selectRoleId: null,
      //成员管理对话框标题
      accountRoleTitle: null,
      //成员管理对话框是否显示
      accountRoleOpen: false,
      // 会员列表数据
      managerAccountRoleList: [],
      managerAccountRoleTotal: 0,
      options: [],
      defaultProps: {
        children: "children",
        label: "gitLabel",
      },
      onCheckNodeIds: [],
      onCheckNode: [],
      // 选择的组件
      editCheckd:null , 
      // 项目表单数据
      form: {
        namespace: "",
        projectId: "",
        autocreate: "",
        projectName: "",
      },
    };
  },
  mounted() {
    var seedProjectCode = sessionStorage.getItem("seedProjectCode");
    console.log("seed project code = " + seedProjectCode);

    this.form = JSON.parse(seedProjectCode);
  },
  created() {
    // 获取列表
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;

      gitGroupsDatatables(
        this.queryParams,
        this.searchParams,
        this.gitTypeId
      ).then((response) => {
        this.options = response.rows;
        for (let i = 0; i < this.options.length; ++i) {
          this.options[i].gitLabel =
            "【" + this.options[i].name + "】" + this.options[i].description;
          var index = this.onCheckNodeIds.indexOf(this.options[i].id);
          if (index > -1) {
            this.onCheckNode.push(this.options[i]);
          }
        }
        // this.ManagerRoleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getRoles() {
      roleIdsByUserId(this.selectAccountId).then((rep) => {
        this.onCheckNodeIds = rep.data;
      });
    },
    //获取成员列表
    getManagerAccountRoleList() {
      this.roleMemberQueryParams.roleId = this.selectRoleId;
      roleMemberDatatables(this.roleMemberQueryParams).then((res) => {
        this.managerAccountRoleList = res.rows;
        this.managerAccountRoleTotal = res.total;
        this.accountRoleTitle = "会员列表";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.menusDataList = [];
      this.functionIds = null;
      this.form = {
        //默认状态为正常
        hasStatus: 0,
        roleTitle: null,
        gitLabel: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 成员列表搜索按钮操作
    handleManagerAccountQuery() {
      this.roleMemberQueryParams.pageNum = 1;
      this.getManagerAccountRoleList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      const { pageNum, pageSize } = this.queryParams;
      this.queryParams = { pageNum, pageSize };
      this.handleQuery();
    },
    /** 会员列表重置按钮操作 */
    resetManagerAccountRoleQuery() {
      const { pageNum, pageSize } = this.roleMemberQueryParams;
      this.roleMemberQueryParams = { pageNum, pageSize };
      this.handleManagerAccountQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 返回选择结果
    selectRoleItem() {
      return this.ids;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //获取所选选择菜单
      this.findMenusData();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleStatus = row.id || this.ids;
      getManagerRole(roleStatus).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改角色";
      });
      //获取所选选择菜单
      this.findMenusData(roleStatus);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.functionIds === null) {
            //如果未选择具体服务,则报警
            this.$confirm("请在右侧选择功能菜单!", "警告", {
              confirmButtonText: "确定",
              type: "warning",
            });
          } else if (this.form.id != null) {
            updateFunctions(this.form, this.functionIds).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            saveFunctions(this.form, this.functionIds).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var ids = this.ids.join(",");
      const roleStatuss = row.id || ids;
      this.$confirm("是否确认删除数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delManagerRole(roleStatuss);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 状态修改 **/
    handleStatusChange(row) {
      return changeStatusManagerRole(row.id, row.status).then((response) => {
        if (response.code == 200) {
          this.msgSuccess("操作成功");
        }
      });
    },
    /** 修改字段状态 **/
    chanageFile(value, filed, id) {
      return changeManagerRoleField(value, filed, id).then((response) => {
        if (response.code == 200) {
          this.msgSuccess("操作成功");
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有【请填写功能名称】数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportManagerRole(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    //成员管理操作
    handleMember(row) {
      this.accountRoleOpen = true;
      this.selectRoleId = row.id;
      this.getManagerAccountRoleList();
    },
    //查询菜单数据
    findMenusData(roleId) {
      //使用表单提交
      let formData = new FormData();
      //测试用
      formData.append("NOT_NULL", "DONT_NULL");
      if (roleId != null) {
        formData.append("roleId", roleId);
      }

      var select = [];
      menusData(formData)
        .then((res) => {
          //格式化树形List
          this.menusDataList = this.handleTree(
            res.data,
            "id",
            "resourceParent"
          );

          res.data.forEach(function (item) {
            if (item.checked) {
              select.push(item.id);
            }
          });
        })
        .then(() => {
          select.forEach((value) => {
            this.$refs.menusTree.setChecked(value, true, false);
          });
        });
    },
    // 树形节点复选框事件
    checkMenuTree(data) {
      //获取全选与半选id
      var res = this.$refs.menusTree
        .getCheckedKeys()
        .concat(this.$refs.menusTree.getHalfCheckedKeys());
      this.functionIds = res.join(",");
    },
    // 读取时间选择器获得的时间
    onChangeReadTimes(timeName) {
      this.queryParams["condition[" + timeName + "|geTime]"] =
        this.queryParams.times[0];
      this.queryParams["condition[" + timeName + "|leTime]"] =
        this.queryParams.times[1];
    },

    handleCheckChange(item, checked, indeterminate) {
      if (checked) {
        // this.onCheckNode.push(data);
        this.editCheckd = item
        this.$refs.tree.setCheckedKeys([item.id]);
      } else {
        // var index = this.onCheckNode.indexOf(data);
        // this.onCheckNode.splice(index, 1);
        if(this.editCheckd.id === item.id){
            this.$refs.tree.setCheckedKeys([item.id]);
        }
      }
    },
    appAuthSubmit() {
      this.generatorGit() ; 
    },
    generatorGit(formName, item) {
      const loading = this.$loading({
        lock: true,
        text: "工程正在生成，预计1分钟，请耐心等待...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      console.log('editCheckd = ' + this.editCheckd) ;

      // this.form.gitType = this.gitType;
      this.form.group = this.editCheckd ;
      this.form.gitTypeId = this.gitTypeId ; 
      this.form.gitType = this.selectGit ; 

      uploadGitProject(this.form).then(
        (response) => {
          loading.close();
          if (response.code !== 200) {
            this.$message({
              message: "工程生成失败:" + response.msg,
              type: "waring",
            });
          } else {
            this.$message({
              message: "工程生成成功" , 
              type: "success",
            });
            var projectId = response.projectId ;
            var toPath = '/build/overview/' + projectId ;
            this.$router.push({path: toPath});
          }
        },
        (error) => {
          loading.close();
        }
      );
    },

  },
};
</script>